package com.xuanjia.smart_interview.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuanjia.smart_interview.common.ErrorCode;
import com.xuanjia.smart_interview.constant.CommonConstant;
import com.xuanjia.smart_interview.exception.BusinessException;
import com.xuanjia.smart_interview.exception.ThrowUtils;
import com.xuanjia.smart_interview.mapper.QuestionBankQuestionMapper;
import com.xuanjia.smart_interview.model.dto.questionBankQuestion.QuestionBankQuestionQueryRequest;
import com.xuanjia.smart_interview.model.entity.QuestionBankQuestion;
import com.xuanjia.smart_interview.model.entity.Question;
import com.xuanjia.smart_interview.model.entity.QuestionBank;
import com.xuanjia.smart_interview.model.entity.User;
import com.xuanjia.smart_interview.model.vo.QuestionBankQuestionVO;
import com.xuanjia.smart_interview.model.vo.UserVO;
import com.xuanjia.smart_interview.service.QuestionBankQuestionService;
import com.xuanjia.smart_interview.service.QuestionBankService;
import com.xuanjia.smart_interview.service.QuestionService;
import com.xuanjia.smart_interview.service.UserService;
import com.xuanjia.smart_interview.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 题库题目关联啊服务实现
 *
 * @author <a href="give you fight">程序员宣佳</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@Service
@Slf4j
public class QuestionBankQuestionServiceImpl extends ServiceImpl<QuestionBankQuestionMapper, QuestionBankQuestion> implements QuestionBankQuestionService {

    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private QuestionService questionService;

    @Resource
    private QuestionBankService questionBankService;

    @Autowired
    @Lazy
    private QuestionBankQuestionService questionBankQuestionService;

    /**
     * 校验数据
     *
     * @param questionBankQuestion
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validQuestionBankQuestion(QuestionBankQuestion questionBankQuestion, boolean add) {
        ThrowUtils.throwIf(questionBankQuestion == null, ErrorCode.PARAMS_ERROR);
        // 题目和题库必须存在
        Long questionId = questionBankQuestion.getQuestionId();
        if (questionId != null) {
            Question question = questionService.getById(questionId);
            ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        Long questionBankId = questionBankQuestion.getQuestionBankId();
        if (questionBankId != null) {
            QuestionBank questionBank = questionBankService.getById(questionBankId);
            ThrowUtils.throwIf(questionBank == null, ErrorCode.NOT_FOUND_ERROR, "题库不存在");
        }

        // 不需要校验
//        // todo 从对象中取值
//        String title = questionBankQuestion.getTitle();
//        // 创建数据时，参数不能为空
//        if (add) {
//            // todo 补充校验规则
//            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
//        }
//        // 修改数据时，有参数则校验
//        // todo 补充校验规则
//        if (StringUtils.isNotBlank(title)) {
//            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
//        }
    }

    /**
     * 获取查询条件
     *
     * @param questionBankQuestionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionBankQuestion> getQueryWrapper(QuestionBankQuestionQueryRequest questionBankQuestionQueryRequest) {
        QueryWrapper<QuestionBankQuestion> queryWrapper = new QueryWrapper<>();
        if (questionBankQuestionQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = questionBankQuestionQueryRequest.getId();
        Long notId = questionBankQuestionQueryRequest.getNotId();
        String sortField = questionBankQuestionQueryRequest.getSortField();
        String sortOrder = questionBankQuestionQueryRequest.getSortOrder();
        Long questionBankId = questionBankQuestionQueryRequest.getQuestionBankId();
        Long questionId = questionBankQuestionQueryRequest.getQuestionId();
        Long userId = questionBankQuestionQueryRequest.getUserId();
        // todo 补充需要的查询条件
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionBankId), "questionBankId", questionBankId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取题库题目关联封装
     *
     * @param questionBankQuestion
     * @param request
     * @return
     */
    @Override
    public QuestionBankQuestionVO getQuestionBankQuestionVO(QuestionBankQuestion questionBankQuestion, HttpServletRequest request) {
        // 对象转封装类
        QuestionBankQuestionVO questionBankQuestionVO = QuestionBankQuestionVO.objToVo(questionBankQuestion);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = questionBankQuestion.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionBankQuestionVO.setUser(userVO);
        // endregion

        return questionBankQuestionVO;
    }

    /**
     * 分页获取题库题目关联封装
     *
     * @param questionBankQuestionPage
     * @param request
     * @return
     */
    @Override
    public Page<QuestionBankQuestionVO> getQuestionBankQuestionVOPage(Page<QuestionBankQuestion> questionBankQuestionPage, HttpServletRequest request) {
        List<QuestionBankQuestion> questionBankQuestionList = questionBankQuestionPage.getRecords();
        Page<QuestionBankQuestionVO> questionBankQuestionVOPage = new Page<>(questionBankQuestionPage.getCurrent(), questionBankQuestionPage.getSize(), questionBankQuestionPage.getTotal());
        if (CollUtil.isEmpty(questionBankQuestionList)) {
            return questionBankQuestionVOPage;
        }
        // 对象列表 => 封装对象列表
        List<QuestionBankQuestionVO> questionBankQuestionVOList = questionBankQuestionList.stream().map(questionBankQuestion -> {
            return QuestionBankQuestionVO.objToVo(questionBankQuestion);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionBankQuestionList.stream().map(QuestionBankQuestion::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        questionBankQuestionVOList.forEach(questionBankQuestionVO -> {
            Long userId = questionBankQuestionVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionBankQuestionVO.setUser(userService.getUserVO(user));
        });
        // endregion

        questionBankQuestionVOPage.setRecords(questionBankQuestionVOList);
        return questionBankQuestionVOPage;
    }

    /**
     * 向题库批量插入题目
     * @param questionIdList
     * @param questionBankId
     * @param loginUser
     */
    @Override
    public void batchAddQuestionsToBank(List<Long> questionIdList, Long questionBankId, User loginUser) {
        // 参数校验
        ThrowUtils.throwIf(CollUtil.isEmpty(questionIdList), ErrorCode.PARAMS_ERROR, "题目列表为空");
        ThrowUtils.throwIf(questionBankId == null || questionBankId <= 0, ErrorCode.PARAMS_ERROR, "题库非法");
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);

        // 检查题目 id 是否存在
        List<Question> questionList = questionService.listByIds(questionIdList);

        LambdaQueryWrapper<Question> questionLambdaQueryWrapper = new LambdaQueryWrapper<Question>()
                .select(Question::getId)
                .in(Question::getId, questionList);
        List<Long> validQuestionIdList = questionService.listObjs(questionLambdaQueryWrapper, object -> (Long) object);
        ThrowUtils.throwIf(CollUtil.isEmpty(validQuestionIdList),ErrorCode.PARAMS_ERROR,"合法的题目为空");
        LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                .eq(QuestionBankQuestion::getQuestionBankId, questionBankId)
                .in(QuestionBankQuestion::getQuestionId, validQuestionIdList);
        List<QuestionBankQuestion> existQuestionList = this.list(lambdaQueryWrapper);
        Set<Long> existQuestionIdSet = existQuestionList.stream()
                .map(QuestionBankQuestion::getQuestionId)
                .collect(Collectors.toSet());
        validQuestionIdList = existQuestionIdSet.stream()
                .filter(questionId -> {
                    return !existQuestionIdSet.contains(questionId);
                })
                .collect(Collectors.toList());
        ThrowUtils.throwIf(CollUtil.isEmpty(validQuestionIdList), ErrorCode.PARAMS_ERROR, "题目重复提交!");

        // 检查题库 id 是否存在
        QuestionBank questionBank = questionBankService.getById(questionBankId);
        ThrowUtils.throwIf(questionBank == null, ErrorCode.NOT_FOUND_ERROR, "题库不存在");

        //自定义线程池 ( IO 密集型 线程池)
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                20,//核心线程数
                50,//最大线程数
                60L,//线程空闲存活时间
                TimeUnit.SECONDS,//存活时间单位
                new LinkedBlockingDeque<>(10000),//阻塞队列容量
                new ThreadPoolExecutor.CallerRunsPolicy()//拒绝策略，由调用线程处理任务
        );
        //保证所有批次任务
        List<CompletableFuture<Void>> futures = new ArrayList<>();

        //分批处理长事务
        int batchSize = 1000;
        int totalBatchSize = validQuestionIdList.size();
        // 执行插入
        for (int i = 0 ; i < totalBatchSize; i += batchSize) {
            QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
            List<Long> subList = validQuestionIdList.subList(i, Math.min(i + batchSize, totalBatchSize));
            List<QuestionBankQuestion> questionBankQuestions = subList.stream()
                    .map(questionId -> {
                        questionBankQuestion.setQuestionId(questionId);
                        questionBankQuestion.setQuestionBankId(questionBankId);
                        questionBankQuestion.setUserId(loginUser.getId());
                        return questionBankQuestion;
                    }).collect(Collectors.toList());

            //使用事务处理每批数据
            //获取代理
            QuestionBankQuestionService bankQuestionService = (QuestionBankQuestionServiceImpl) AopContext.currentProxy();

            //异步处理每批数据，将任务添加到异步处理列表
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                bankQuestionService.batchAddQuestionsToBankInner(questionBankQuestions);
            }, threadPoolExecutor);
            futures.add(future);

            //等待所有批次完成操作
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            //关闭线程池
            threadPoolExecutor.shutdown();
        }
    }

    /**
     * 对事件进行分批数据处理，避免长事务操作
     * @param questionBankQuestions
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchAddQuestionsToBankInner(List<QuestionBankQuestion> questionBankQuestions) {
        try {
            boolean saveBatch = questionBankQuestionService.saveBatch(questionBankQuestions);
            ThrowUtils.throwIf(!saveBatch, ErrorCode.PARAMS_ERROR, "题库插入失败");
        } catch (DataIntegrityViolationException dataIntegrityViolationException){
            log.info("数据库唯一键冲突或违反其他约束，插入失败，信息：{}",dataIntegrityViolationException.getMessage());
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"题目已存在题库中，无法添加");
        }catch (DataAccessException dataAccessException) {
            log.info("数据库连接问题、事务问题等导致操作失败，错误信息：{}", dataAccessException.getMessage());
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "数据库操作失败");
        }catch (Exception exception){
            log.info("其他未知错误,错误信息:{}",exception.getMessage());
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "题目添加失败");
        }
    }




    /**
     * 批量删除题目信息
     * @param questionIdList
     * @param questionBankId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchRemoveQuestionToBank(List<Long> questionIdList, Long questionBankId){
        ThrowUtils.throwIf(CollUtil.isEmpty(questionIdList), ErrorCode.PARAMS_ERROR,"题目不存在");
        ThrowUtils.throwIf(questionBankId == null || questionBankId <= 0, ErrorCode.PARAMS_ERROR,"题库不存在");
        for (Long questionId : questionIdList){
        LambdaQueryWrapper<QuestionBankQuestion> bankQuestionLambdaQueryWrapper = new LambdaQueryWrapper<QuestionBankQuestion>()
                .eq(QuestionBankQuestion::getQuestionBankId, questionBankId)
                .eq(QuestionBankQuestion::getQuestionId, questionId);

        boolean result = this.remove(bankQuestionLambdaQueryWrapper);
        if (!result) throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
    }

    /**
     * 批量删除题目
     * @param questionIdList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteQuestion(List<Long> questionIdList){
        ThrowUtils.throwIf(questionIdList == null, ErrorCode.PARAMS_ERROR, "删除题目信息为空！");
        for (Long questionId : questionIdList){
            boolean result = questionService.removeById(questionId);
            if(!result){ throw new BusinessException(ErrorCode.PARAMS_ERROR); }
            LambdaQueryWrapper<QuestionBankQuestion> questionBankLambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                    .eq(QuestionBankQuestion::getQuestionId, questionId);
            boolean result1 = questionBankQuestionService.remove(questionBankLambdaQueryWrapper);
            if (!result1){ throw new BusinessException(ErrorCode.PARAMS_ERROR);}
        }
    }
}
